package com.bee.sample.ch19.controller;

import com.bee.sample.ch19.service.OrderService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Random;

@Controller
public class BarrierController {
  @Autowired
  CuratorFramework zkClient ;

  @RequestMapping("/barrier.html")
  public @ResponseBody
  String barrier() throws Exception{
    DistributedBarrier barrier = new DistributedBarrier(zkClient,"/jobs" );
    barrier.setBarrier();
    System.out.println("等待 "+Thread.currentThread().getId());
    barrier.waitOnBarrier();
    System.out.println("开始运行 "+Thread.currentThread().getId());
    return "success";
  }

  @RequestMapping("/start.html")
  public @ResponseBody
  String removeBarrier() throws Exception{
    DistributedBarrier barrier = new DistributedBarrier(zkClient,"/jobs" );
    System.out.println("开始执行");
    barrier.removeBarrier();
    return "success";
  }


  String path = "/doubleBarrier";

  @RequestMapping("/doubleBarrier.html")
  public @ResponseBody String  doubleBarrier() throws Exception{
    //期望3个任务
    DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(zkClient, path, 3);
    System.out.println("任务等待执行 " + Thread.currentThread().getId());
    barrier.enter();
    System.out.println("开始执行" + Thread.currentThread().getId());
    Thread.sleep(new Random().nextInt(1000));
    barrier.leave();
    System.out.println("自行完毕" + Thread.currentThread().getId());
    return "success";
  }

}
